<template>
    <tnxel-select v-model="model" :items="availablePhysicalTypes" value-name="name" text-name="name" filterable/>
</template>

<script>
import ModelingApp from '@/logic/modeling/entity/ModelingApp.js';
import PersistUtil from '@/logic/modeling/util/persist.js';

export default {
    props: {
        modelValue: String,
        app: {
            type: ModelingApp,
            required: true,
        },
        logicType: String,
        arrayed: Boolean,
    },
    emits: ['update:modelValue', 'change'],
    data() {
        return {
            model: this.modelValue,
        };
    },
    computed: {
        availablePhysicalTypes() {
            return PersistUtil.getAvailablePhysicalTypes(this.app);
        },
        currentType() {
            if (this.model) {
                let types = this.availablePhysicalTypes;
                if (types) {
                    for (let type of types) {
                        if (type.name === this.model) {
                            return type;
                        }
                    }
                }
            }
            return undefined;
        },
        filteredTypes() {
            let types = this.availablePhysicalTypes;
            if (types && this.logicType) {
                let logicType = PersistUtil.getFinalLogicType(this.app, this.logicType);
                return types.filter(type => type.supports(logicType));
            }
            return [];
        },
    },
    watch: {
        modelValue(value) {
            this.model = value;
        },
        model(value) {
            this.$emit('update:modelValue', value);
            this.$nextTick(() => {
                this.$emit('change', this.currentType);
            });
        },
        logicType() {
            this.updateModel();
        },
        arrayed() {
            this.updateModel();
        },
    },
    mounted() {
        if (!this.model) {
            this.updateModel();
        }
    },
    methods: {
        updateModel() {
            let defaultType = PersistUtil.getDefaultPhysicalType(this.app, this.logicType, this.arrayed);
            if (!defaultType) {
                defaultType = this.filteredTypes[0];
            }
            if (defaultType) {
                this.model = defaultType.name;
            } else {
                this.model = '';
            }
        }
    }
}
</script>

<style lang="scss" scoped>

</style>
